package com.fxust.thread;

/**
 * @auto johnking
 * @create 2017-12-17 下午9:20
 **/

import com.fxust.common.CommonDefine;
import com.fxust.dao.ThirdTableDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.imageio.stream.FileImageOutputStream;


public class DownLoadPicDetailThread extends Thread{

    private static Logger logger = LoggerFactory.getLogger(DownLoadPicDetailThread.class);
    private String choosePath;
    int cp;
    int pageStart;
    int pageEnd;

    public DownLoadPicDetailThread(String choosePath,int cp, int pageStart,int pageEnd){
        this.choosePath = choosePath;
        this.cp = cp;
        this.pageStart = pageStart;
        this.pageEnd = pageEnd;


    }
    @Override
    public void run() {

        //分页查询数据
        String querySql = CommonDefine.queryDetailSql;
        String[] fields = {"humanname","humancid","facepicurl"};
        querySql = replaceSql(querySql,pageStart,pageEnd);
        long startTime = System.currentTimeMillis();
        ThirdTableDao dao = new ThirdTableDao();
        List<Map<String, Object>> queryList = dao.queryBlobPicData(querySql, fields);
        logger.info("查询"+queryList.size()+"条数据,耗时:"+(System.currentTimeMillis() - startTime));

        //保存数据到本地文件夹
        startTime = System.currentTimeMillis();
        savePicDataToLocal(queryList);
        logger.info("图片保存到本地,耗时:"+(System.currentTimeMillis() - startTime));
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    /**
     * sql替换
     * @param sql
     * @param pageStart
     * @param pageEnd
     * @return
     */
    private String replaceSql(String sql, int pageStart,int pageEnd) {
        String resultSql = sql.replace("{ENDNUM}", String.valueOf(pageEnd));
        resultSql = resultSql.replace("{STARTNUM}", String.valueOf(pageStart));
        return resultSql;
    }
    /**
     * 保存图片到本地路径
     * @author fgq 2017年11月22日 下午4:02:40
     * @param queryList
     */
    private void savePicDataToLocal(List<Map<String, Object>> queryList){
        if(queryList != null && queryList.size() > 0){
            FileImageOutputStream imageOutput = null;
            for (Map<String, Object> resultMap : queryList) {
                //获取数据
                String username = (String)resultMap.get("humanname");
                String credentialsnum = (String)resultMap.get("humancid");
                byte[] xpUrl = (byte[])resultMap.get("facepicurl");

                if (xpUrl != null && xpUrl.length > 1) {
                    //获取根路径
                    int rootNum = cp / 100;
                    String rootDir = String.valueOf(rootNum);
                    String filePath = choosePath + "/" + rootDir + "/";
                    filePath = filePath + String.valueOf(pageStart);
                    boolean isOk = createFilePath(filePath);
                    if(isOk){
                        String targetFile = filePath + "/" + username + "_" + credentialsnum + ".jpg";
                        try{
                            // 文件写入本地
                            File file = new File(targetFile);
                            imageOutput = new FileImageOutputStream(file);
                            imageOutput.write(xpUrl, 0, xpUrl.length);
                            imageOutput.flush();
                        }catch(Exception e){
                            logger.error("图片写入本地错误",e);
                        }
                    }
                }
            }
            try {
                imageOutput.close();
            } catch (IOException e) {
                logger.error("文件写入流关闭失败");
            }
        }
    }

    private boolean createFilePath(String filePath) {
        File folder = new File(filePath);
        if (folder.exists() == false) {
            boolean isOK = folder.mkdirs();
            if (!isOK) {
                logger.error("创建保存文件夹出错,文件夹地址" + filePath);
                return false;
            }
        }
        return true;
    }
}
